class User::FriendController < ApplicationController
  before_filter :validate_logged
  
  def index
    list_your_friends
    render :action => 'list_your_friends'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list_your_friends
    #@friend_pages, @friends = paginate :friends, :per_page => 10
    friend_users = @user.users_given_friendship()
    @friend_users = WillPaginate::Collection.create((params[:page] or 1).to_i, 24) do |pager|
      pager.replace( friend_users[pager.offset, pager.per_page].to_a )
      
      unless pager.total_entries
        pager.total_entries = friend_users.size
      end
    end
  end
  
  def list_friend_catalogs
    friend_users = @user.users_gave_you_friendship()
    @friend_users = WillPaginate::Collection.create((params[:page] or 1).to_i, 10) do |pager|
      pager.replace( friend_users[pager.offset, pager.per_page].to_a )
      
      unless pager.total_entries
        pager.total_entries = friend_users.size
      end
    end
  end

  def new
    @friend = Friend.new
  end

  def create
    friend_users = User.find(:all, :conditions =>  ["username = :username", params[:friend]])
    if friend_users.size < 1
      info "User doesn't exist", :error
      redirect_to :action => 'new'
      return
    elsif friend_users.size > 1
      info "Something VERY wrong is going on", :error
      redirect_to :action => 'new'
      return
    end
    if friend_users[0] == @user
      info "Cannot add yourself to friends", :error
      redirect_to :action => 'new'
      return
    end
    if Friend.find(:all,
        :conditions => "user_id_primary = '#{@user.id}' and user_id_secondary = '#{friend_users[0].id}'" ).size > 0
      info "User #{friend_users[0].username} is already your friend", :error
      redirect_to :action => 'new'
      return
    end
    @friend = Friend.new(:user_id_primary => @user.id, :user_id_secondary => friend_users[0].id)
    if @friend.save
      flash[:notice] = 'Friend was successfully created.'
      redirect_to :action => 'index'
    else
      render :action => 'new'
    end
  end

  def remove
    for friend_user in Friend.find(:all, :conditions => "user_id_primary = '#{@user.id}' and user_id_secondary = '#{params[:id]}'" )
      friend_user.destroy
    end
    redirect_to :action => 'index'
  end
  
  private
  
  def validate_logged
    if session[:user_id]
      @user = User.find(session[:user_id])
    else
      @user = nil
    end
    if @user.nil?
      info "Please log in"
      redirect_to :controller => login, :action => login
    end
  end
end
